/**
 * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.slayer.service.impl;

import java.util.List;
import java.util.Locale;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Contact;
import com.liferay.portal.model.ListType;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.model.VirtualHost;
import com.liferay.portal.security.auth.CompanyThreadLocal;
import com.liferay.portal.service.ListTypeServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextThreadLocal;
import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
import com.liferay.portal.service.persistence.VirtualHostUtil;
import com.slayer.service.base.BridgeLocalServiceBaseImpl;

/**
 * The implementation of the bridge local service.
 *
 * <p>
 * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link com.slayer.service.BridgeLocalService} interface.
 *
 * <p>
 * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
 * </p>
 *
 * @author Ahmed Hasan
 * @see com.slayer.service.base.BridgeLocalServiceBaseImpl
 * @see com.slayer.service.BridgeLocalServiceUtil
 */
public class BridgeLocalServiceImpl extends BridgeLocalServiceBaseImpl {
	public boolean isEmailExists(long companyId, String emailAddress) {
		boolean exists = false;
		
		try {
			User user = userLocalService.fetchUserByEmailAddress(companyId, emailAddress);
			
			exists = Validator.isNotNull(user);
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		return exists;
	}
	
	public Organization addUserOrganisation(long userId, long parentOrganizationId, String name) {

		Organization organization = null;
		
		try {
			organization = organizationLocalService.addOrganization(userId, parentOrganizationId, name, false);
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		if (Validator.isNotNull(organization)) {
			
			try {
				organizationLocalService.addUserOrganization(userId, organization.getOrganizationId());
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			assignOrganizationRole(userId, organization, RoleConstants.ORGANIZATION_ADMINISTRATOR);	
		}
		
		return organization;
	}
	
	private void assignOrganizationRole(long userId, Organization organization, String roleName) {
		long companyId = CompanyThreadLocal.getCompanyId();
		long roleId = 0l;
		
		try {
			Role role = RoleLocalServiceUtil.fetchRole(companyId, roleName);
			
			if (Validator.isNull(role)) {
				long classPK = counterLocalService.increment();
				//role = RoleLocalServiceUtil.addRole(userId, Role.class.getName(), classPK, roleName, titleMap, descriptionMap, RoleConstants.TYPE_ORGANIZATION, 0, null);
			}
			
			roleId = role.getRoleId();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		
		try {
			UserGroupRoleLocalServiceUtil.addUserGroupRoles(userId, organization.getGroupId(), new long[] { roleId });
		} catch (SystemException e) {
			e.printStackTrace();
		}
	}
	
	/* first add the entry in the user table  */
	public User addAdminUser(long creatorUserId, String firstName, String lastName,
										long countryId,String emailAddress,	String jobTitle, String organizationName) {
		
		long companyId = CompanyThreadLocal.getCompanyId();
		ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
		User user = null;
		try {
			user = userLocalService.addUser(creatorUserId, companyId, true,
					null, null, true, null, emailAddress,
					0, null, Locale.US, firstName, StringPool.BLANK, lastName,
					0, 0, false, 1, 1,
					1, jobTitle, null, null, null,
					null, true, serviceContext);
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		// insert a record into the "Address" table for this user
		try {
			addressLocalService.addAddress(user.getUserId(),
					User.class.getName(), user.getUserId(), "Not Specified",
					StringPool.BLANK, StringPool.BLANK, "Not Specified",
					"Not Specified", 0l, countryId,
					getType(Contact.class.getName(), "address"), false, true,
					serviceContext);
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
		return user;
	}
	/* this is the default type available when creating the user {business,,,} */
	private int getType(String className, String type) {
			int _type = 0;
			try {
				List<ListType> listTypes = ListTypeServiceUtil.getListTypes(className + StringPool.PERIOD + type);
				for (ListType listType: listTypes) {
					if (listType.getName().equalsIgnoreCase("business")) {
						_type = listType.getListTypeId();
						break;
					}
				}
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			return _type;
	}
	//code checks if email exists in the user table or not
	public  boolean isEmailNotExists(long companyId,String emailAddress){
		
		boolean flag=true;
		User user=null;
		try {
			user=userLocalService.fetchUserByEmailAddress(companyId, emailAddress);
		} catch (SystemException e) {
			e.printStackTrace();
		}catch(Exception e2){
		}
		if(Validator.isNotNull(user)){
			flag=false;
		}
		return flag;
	}
	
	public User addUser(long creatorUserId,long organizationId,String firstName, String lastName,long countryId,String emailAddress,String jobTitle) {
	    
	    long companyId = CompanyThreadLocal.getCompanyId();
	    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
	    User user = null;
	    try {
	        user = userLocalService.addUser(creatorUserId, companyId, true,
	                null, null, true, null, emailAddress,
	                0, null, Locale.US, firstName, StringPool.BLANK, lastName,
	                0, 0, false, 1, 1,
	                1, jobTitle, null, null, null,
	                null, true, serviceContext);
	    } catch (PortalException e) {
	        e.printStackTrace();
	    } catch (SystemException e) {
	        e.printStackTrace();
	    }
	        try {
				organizationLocalService.addUserOrganization(user.getUserId(), organizationId);
			} catch (SystemException e) {
				e.printStackTrace();
			}
	        try {
	            addressLocalService.addAddress(user.getUserId(),
	                    User.class.getName(), user.getUserId(), "Not Specified",
	                    StringPool.BLANK, StringPool.BLANK, "Not Specified",
	                    "Not Specified", 0l, countryId,
	                    getType(Contact.class.getName(), "address"), false, true,
	                    serviceContext);
	        } catch (PortalException e) {
	            e.printStackTrace();
	        } catch (SystemException e) {
	            e.printStackTrace();
	        }
	    return user;
	}
	public boolean isOrganizationNotExists(long companyId,String organizationName){

		boolean flag=true;
		Organization org=null;
		try {
			org=organizationLocalService.fetchOrganization(companyId, organizationName);
		} catch (SystemException e) {
		e.printStackTrace();
		}
		catch(Exception e2){
		}
		if(Validator.isNotNull(org)){
			flag=false;
		}
		return flag;
	}
	public boolean isVirtualHostNotExists(String hostName){

		boolean flag=true;
		VirtualHost vh=null;
		try {
			vh=VirtualHostUtil.fetchByHostname(hostName);
		} catch (SystemException e) {
			e.printStackTrace();
		}
		catch(Exception e2){
		}
		if(Validator.isNotNull(vh)){
			flag=false;
		}
		return flag;
	}	
}